package gwtappcontainer.server.apis.content;

import static com.googlecode.objectify.ObjectifyService.ofy;
import gwtappcontainer.server.DatastoreNamespaces;
import gwtappcontainer.shared.apis.content.ContentProp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import com.google.appengine.api.NamespaceManager;
import com.google.gson.Gson;
import com.googlecode.objectify.ObjectifyService;

class ContentRepository {
	
	static {
		ObjectifyService.factory().register(ContentEntity.class);
	}
	
	private final String NAMESPACE = DatastoreNamespaces.CONTENT;	
	
	private Logger logger = Logger.getLogger(ContentAPI.class.getName());
	
	ContentProp setContent(String html, String tag, boolean publish) {
		NamespaceManager.set(NAMESPACE);
		
		tag = tag.toLowerCase();
		ContentEntity entity = ofy().load().type(ContentEntity.class).
				filter("tag", tag).first().get();
		
		if (null == entity)
			entity = new ContentEntity();
				
		entity.html = html;
		entity.tag = tag;
		entity.publish = publish;
		
		ofy().save().entity(entity).now();
		
		return entity.toProp();		
	}
	
	ContentProp getContent(String tag) {
		NamespaceManager.set(NAMESPACE);
		
		tag = tag.toLowerCase();
		ContentEntity entity = ofy().load().type(ContentEntity.class).
				filter("tag", tag).first().get();
		
		logger.info("fetched entity: " + new Gson().toJson(entity));
		
		if (null == entity)
			return null;
		
		return entity.toProp();
	}
	
	Map<String, String> getAllValidPublishedContents() {
		NamespaceManager.set(NAMESPACE);
		
		List<ContentEntity> all = ofy().load().type(ContentEntity.class).list();
		
		Map<String, String> allPublishedContents = new HashMap<String, String>();
		
		for (ContentEntity entity : all) {
			if (true == entity.publish) {
				if ((entity.html != null) && (! entity.html.equals("")))
					allPublishedContents.put(entity.tag, entity.html);
			}
		}
		
		return allPublishedContents;				
	}		
}
